package com.hxzon.netty.statistics.server;

import java.net.InetSocketAddress;
import java.util.concurrent.Executors;

import org.jboss.netty.bootstrap.ServerBootstrap;
import org.jboss.netty.channel.ChannelPipelineFactory;
import org.jboss.netty.channel.socket.nio.NioServerSocketChannelFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.hxzon.netty.statistics.util.StatisticsConfig;

public class StatisticsServer {
    public static void startServer(ChannelPipelineFactory cpf, int port) {
        int workerCount = StatisticsConfig.getWorkerCount();
        if (workerCount <= 0) {
            workerCount = Runtime.getRuntime().availableProcessors() * 2;
        }
        ServerBootstrap bootstrap = new ServerBootstrap(new NioServerSocketChannelFactory(//
                Executors.newCachedThreadPool(), Executors.newCachedThreadPool(), workerCount)//
        );
        bootstrap.setPipelineFactory(cpf);
        bootstrap.bind(new InetSocketAddress(port));
    }

    public static void main(String[] args) throws Exception {
        ApplicationContext spring = new ClassPathXmlApplicationContext("classpath:/application*.xml");
        StatisticsServer.startServer(new StatisticsServerPipelineFactory(spring), StatisticsConfig.getPort());
    }

}
